//
//  QLMotionManager.m
//  QLCustomCamera_Example
//
//  Created by 李强 on 2020/9/2.
//  Copyright © 2020 李强LiQ. All rights reserved.
//

#import "QLMotionManager.h"
#import <CoreMotion/CoreMotion.h>

@interface QLMotionManager ()

@property (nonatomic,strong)CMMotionManager *motionManager;

@end

@implementation QLMotionManager

-(instancetype)init
{
    if (self = [super init]) {
        _motionManager = [[CMMotionManager alloc]init];
        _motionManager.deviceMotionUpdateInterval = 1/15.0;
        if (_motionManager.deviceMotionAvailable) {
            _motionManager = nil;
            return self;
        }
        [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
            [self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
        }];
    }
    return self;
}

-(void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion
{
    double x = deviceMotion.gravity.x;
    double y = deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x)) {
        if (y >= 0) {
            _deviceOrientation = UIDeviceOrientationPortraitUpsideDown;
            _videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
            _interfaceOrientation = UIInterfaceOrientationPortraitUpsideDown;
        }else{
            _deviceOrientation = UIDeviceOrientationPortrait;
            _videoOrientation = AVCaptureVideoOrientationPortrait;
            _interfaceOrientation = UIInterfaceOrientationPortrait;
        }
    }else{
        if (x >= 0) {
            _deviceOrientation = UIDeviceOrientationLandscapeRight;
            _videoOrientation = AVCaptureVideoOrientationLandscapeRight;
            _interfaceOrientation = UIInterfaceOrientationLandscapeRight;
        }else{
            _deviceOrientation = UIDeviceOrientationLandscapeLeft;
            _videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
            _interfaceOrientation = UIInterfaceOrientationLandscapeLeft;
        }
    }
}

-(void)stopDeviceMotionUpdates
{
    [_motionManager stopDeviceMotionUpdates];
}

@end
